package yaty.lee.toolbox.io;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;
import java.util.Map;

public class IniReader {
    protected LinkedHashMap<String, LinkedHashMap<String, String>> sections;

    public IniReader() {
        super();
        this.sections = new LinkedHashMap<String, LinkedHashMap<String, String>>();
    }

    public LinkedHashMap<String, LinkedHashMap<String, String>> getSections() {
        return this.sections;
    }

    public LinkedHashMap<String, String> getSection(String sectionName) {
        if (this.sections != null) {
            return this.sections.get(sectionName);
        } else {
            return null;
        }
    }

    public String get(String sectionName, String key) {
        Map<String, String> section = this.sections.get(sectionName);
        if (section == null) {
            return "";
        }
        return section.get(key);
    }

    public void load(String fileName) throws FileNotFoundException {
        InputStream is = null;
        try {
            is = new FileInputStream(fileName);
            load(is);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
    }

    public void load(InputStream is) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line = null;
        String lastSectionName = null;
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            if (line.startsWith("#")) {
                continue;
            }
            if (line.startsWith("[") && line.endsWith("]")) {
                lastSectionName = line.substring(1, line.length() - 1);
                this.sections.put(lastSectionName, new LinkedHashMap<String, String>());
            } else if (line.length() == 0) {
                continue;
            } else {
                if (lastSectionName != null) {
                    Map<String, String> section = sections.get(lastSectionName);
                    int index = line.indexOf('=');
                    String key = index > 0 ? line.substring(0, index) : line; // 如果没有等号，直接做key和value
                    String value = index > 0 ? line.substring(index + 1) : line;
                    section.put(key, value);
                }
            }
        }
    }

}
